import org.molamil.commons.ObjectNoDispatcherError;
import org.molamil.commons.ObjectUtil;
import org.molamil.commons.StringUtil;

/**
 * Class that propagates an event from one class to another.
 *
 * @author Jorge Hernandez
 */
class org.molamil.commons.EventUtil{
	
	
	// Constants
	
	public static var ERROR_NO_DISPATCHER:String = "ERROR: \"{event}\" could not be thrown - " +
												   "The originator object does not support events.";
	
	
	// Constructor
	
	private function EventUtil() {}
	
	
	// Functions
	
	/**
	 * Sets the specific <code>proxy</code> object to throw the given <code>event</code> using 
	 * the same <code>eventObject</code> as the <code>originator</code> object.
	 * <br /><br />
	 * Both <code>originator</code> and <code>proxy</code> have to implement the 
	 * <code>mx.events.EventDispatcher</code> methods.
	 * <br /><br />
	 * You can add or overwrite properties of the <code>eventObject</code> using the 
	 * <code>eventProps</code> parameter.
	 * 
	 * @param   originator Original object that throws the event.
	 * @param   proxy Object that will throw the same event as the <code>originator</code>.
	 * @param   event String with the event name.
	 * @param   eventProps [Optional] Object containing properties to be added to the <code>eventObject</code>
	 * 					   thrown, it overwrites properties already defined in <code>eventObject</code>.
	 * @throws  ObjectNoDispatcherError If <code>originator</code> doesn't support the 
	 * 									<code>addEventListener</code> method or <code>proxy</code> doesn't
	 * 									support the <code>dispatchEvent</code> method.
	 */
	public static function propagate(originator:Object, proxy:Object, event:String, eventProps:Object):Void {
		if (originator.addEventListener == null) {
			var msg:String = StringUtil.replace(ERROR_NO_DISPATCHER, "{event}", event);
			throw new ObjectNoDispatcherError(msg);	
		}
		originator.addEventListener(event, function(eventObject:Object):Void {
					if (eventProps != null)
						ObjectUtil.merge(eventObject, eventProps);
					proxy.dispatchEvent(eventObject);
				}
			);
	}
	
	
}